package com.hbhmzy.utils;

import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.util.Log;

import com.hbhmzy.call.SpeexUtil;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;

import static com.hbhmzy.call.WantCallFragment.name;
import static com.hbhmzy.call.WantCallFragment.symbol;

public class EchoClient {
    private static EchoClient echoclient = null;
    private static final int SAMPLE_RATE = 8000; // 采样频率
    public static boolean recording=true;
    int sendbufSize;
    int speexLen = 1024;//一帧音频编码后的byte长度（20ms）与编码质量有关:Speex.open(int compression);
    int oneFrameSize = 1024;//窄带160,宽带320,超宽带640
    SpeexUtil speex = SpeexUtil.getInstance();

    public static EchoClient getInstance(){
        if (echoclient == null) {
            synchronized (SpeexUtil.class) {
                if (echoclient == null) {
                    echoclient = new EchoClient();
                }
            }
        }
        return echoclient;
    }

    public void end(){
        recording=false;
    }

    public void start() throws Exception {
        //先发一条消息通知UDP客户端 name 已上线
        boolean ok1 = UDPUtils.send(name.getBytes(), 11);
        if (ok1)
            Log.e("通知UDP客户端", "发送消息:" + name);
        else
            Log.e("通知UDP客户端", "发往服务端的信息没有成功发出！！！");

        recording=true;
        new Thread(new Runnable() {
            @Override
            public void run() {
                sendbufSize = AudioRecord.getMinBufferSize(SAMPLE_RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
                AudioRecord audioRecorder = new AudioRecord (MediaRecorder.AudioSource.VOICE_COMMUNICATION, SAMPLE_RATE,
                        AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT,sendbufSize*10);
                oneFrameSize = speex.getFrameSize();//160
                int short_read = 0;//存储长度
                short[] buf = new short[oneFrameSize];//存放录制内容
                byte[] speexData = new byte[oneFrameSize];
                audioRecorder.startRecording();// 开始录制


                // 循环发送数据给服务端
                while (recording) {
                    short_read = audioRecorder.read(buf, 0, oneFrameSize);
                    short[] data = new short[short_read];
                    System.arraycopy(buf, 0, data, 0, short_read);
                    speexLen = speex.encode(data, 0, speexData, data.length);//38

                    //将编码后的字节数组 进行copy后进行base64加密 生成新的 数组长度为53
                    byte[] data1=new byte[38];
                    System.arraycopy(speexData, 0, data1, 0, speexLen);
                    byte[] base64_data = android.util.Base64.encode(data1, android.util.Base64.DEFAULT);
                    int oneFrameSpeex_len = base64_data.length+24;// 53+24
//                    int oneFrameSpeex_len = speexLen+4;// 38+4

                    //在发送出去的每个数据包中 加上标识位1#2:或者2#1:
                    int len = 24;
                    byte[] oneFrameSpeex = new byte[oneFrameSpeex_len];
                    for(int i =0;i<len;i++){
                        try {
                            oneFrameSpeex[i]= symbol.getBytes("UTF-8")[i];
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }
//                    System.arraycopy(speexData, 0, oneFrameSpeex, len, speexLen);// 没加密前
                    System.arraycopy(base64_data, 0, oneFrameSpeex, len, base64_data.length);
                    // 开始发送
                    boolean ok = UDPUtils.send(oneFrameSpeex, oneFrameSpeex_len);
                    if (ok)
                        Log.i("EchoClient", "发送消息:"+ Arrays.toString(oneFrameSpeex));
                    else
                        Log.e("EchoClient", "发往服务端的信息没有成功发出！！！");

                    // 3000秒后进入下一次循环
                    //  Thread.sleep(3000);
                }
                audioRecorder.stop();
                audioRecorder.release();
                recording=false;
            }
        }).start();
    }
}
